package com.wmz.picture.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.wmz.picture.annotation.AuthCheck;
import com.wmz.picture.common.BaseResponse;
import com.wmz.picture.common.ResultUtils;
import com.wmz.picture.exception.BusinessException;
import com.wmz.picture.exception.ErrorCode;
import com.wmz.picture.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

import static com.wmz.picture.constant.UserConstant.ADMIN_ROLE;

/**
 * @author lihechun
 * @version 1.0
 * @description: 测试对象存储COS
 * @date: 2024/12/16 22:57
 */
@RestController
@Slf4j
public class FileController {
    @Resource
    private CosManager cosManager;

    /**
     * 测试文件上传
     * @param multipartFile 待上传的文件
     * @return  上传文件后的路径
     */
    @PostMapping("/test/upload")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String fileName = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", fileName);
        File file = null;
        try {
            // 文件上传
            File tempFile = File.createTempFile(fileName, null);
            multipartFile.transferTo(tempFile);
            cosManager.putObject(filePath, tempFile);
            return ResultUtils.success(filePath);
        } catch (Exception e) {
           log.error("file upload error,filepath = {}", filePath,e);
           throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传错误");
        } finally {
            if(file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if(!delete) {
                    log.error("file delete error,filepath = {}", filePath);
                }
            }
        }
    }

    @GetMapping("/test/download")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public void testDownloadFile(String filePath, HttpServletResponse response) {
        try(COSObjectInputStream cosObjectInputStream = cosManager.getObject(filePath).getObjectContent()) {
            // 处理下载的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        }catch (Exception e) {
            log.error("file download error,filePath = ",filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载错误");
        }
    }
}
